package user

import (
	"context"
	"gitee.com/bobo-rs/idea-space-framework/framework/model"
	"gitee.com/bobo-rs/idea-space-framework/pkg/utils"
	"github.com/gogf/gf/v2/errors/gerror"
)

// ValidateAccountLogin 用户认证并验证账户密码登录
func (u *sUser) ValidateAccountLogin(ctx context.Context, in model.UserOauthAccountLoginItem) (*model.UserOauthLoginDetailItem, error) {
	var (
		err    error
		detail = &model.UserOauthLoginDetailItem{}
	)

	// 账户是否存在
	switch utils.IsMobile(in.Account) {
	case true:
		// 手机号密码登录
		err = u.ProcessDetailByMobile(ctx, in.Account, &detail.User)
	default:
		// 账户密码登录
		err = u.ProcessDetailByAccount(ctx, in.Account, &detail.User)
	}
	if err != nil || detail.User == nil {
		return nil, gerror.New(`账号密码错误`)
	}

	// 获取用户账户密码
	userDetail := &model.UserAccountLoginPwdItem{}
	if err = u.ProcessUserDetailByUid(ctx, detail.Id, &userDetail); err != nil {
		return nil, err
	}

	// 验证密码
	if !utils.PasswordVerify(userDetail.PwdHash, in.Pwd, userDetail.PwdSalt) {
		return nil, gerror.New(`登录失败，账号密码错误`)
	}
	return detail, nil
}
